<?php

/**
 * 读取网易歌单数据
 * author:lovefc
 */
header("Content-type:application/json;Charset=utf8");

function getRandomHex($length)
{
    if (function_exists('random_bytes')) {
        return bin2hex(random_bytes($length / 2));
    }
    if (function_exists('mcrypt_create_iv')) {
        return bin2hex(mcrypt_create_iv($length / 2, MCRYPT_DEV_URANDOM));
    }
    if (function_exists('openssl_random_pseudo_bytes')) {
        return bin2hex(openssl_random_pseudo_bytes($length / 2));
    }
}

function bchexdec($hex)
{
    $dec = 0;
    $len = strlen($hex);
    for ($i = 1; $i <= $len; $i++) {
        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
    }
    return $dec;
}

function bcdechex($dec)
{
    $hex = '';
    do {
        $last = bcmod($dec, 16);
        $hex = dechex($last) . $hex;
        $dec = bcdiv(bcsub($dec, $last), 16);
    } while ($dec > 0);
    return $hex;
}

function str2hex($string)
{
    $hex = '';
    for ($i = 0; $i < strlen($string); $i++) {
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0' . $hexCode, -2);
    }
    return $hex;
}

function netease_AESCBC($url, $body)
{
    $modulus = '157794750267131502212476817800345498121872783333389747424011531025366277535262539913701806290766479189477533597854989606803194253978660329941980786072432806427833685472618792592200595694346872951301770580765135349259590167490536138082469680638514416594216629258349130257685001248172188325316586707301643237607';
    $pubkey = '65537';
    $nonce = '0CoJUm6Qyw8W8jud';
    $vi = '0102030405060708';
    if (extension_loaded('bcmath')) {
        $skey = getRandomHex(16);
    } else {
        $skey = 'B3v3kH4vRPWRJFfH';
    }
    $body = json_encode($body);
    if (function_exists('openssl_encrypt')) {
        $body = openssl_encrypt($body, 'aes-128-cbc', $nonce, false, $vi);
        $body = openssl_encrypt($body, 'aes-128-cbc', $skey, false, $vi);
    } else {
        $pad = 16 - (strlen($body) % 16);
        $body = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $nonce, $body . str_repeat(chr($pad), $pad), MCRYPT_MODE_CBC, $vi));
        $pad = 16 - (strlen($body) % 16);
        $body = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $skey, $body . str_repeat(chr($pad), $pad), MCRYPT_MODE_CBC, $vi));
    }
    if (extension_loaded('bcmath')) {
        $skey = strrev(utf8_encode($skey));
        $skey = bchexdec(str2hex($skey));
        $skey = bcpowmod($skey, $pubkey, $modulus);
        $skey = bcdechex($skey);
        $skey = str_pad($skey, 256, '0', STR_PAD_LEFT);
    } else {
        $skey = '85302b818aea19b68db899c25dac229412d9bba9b3fcfe4f714dc016bc1686fc446a08844b1f8327fd9cb623cc189be00c5a365ac835e93d4858ee66f43fdc59e32aaed3ef24f0675d70172ef688d376a4807228c55583fe5bac647d10ecef15220feef61477c28cae8406f6f9896ed329d6db9f88757e31848a6c2ce2f94308';
    }
    $api['url'] = str_replace('/api/', '/weapi/', $url);
    $api['body'] = array(
        'params'    => $body,
        'encSecKey' => $skey,
    );
    return $api;
}

function setHead()
{
    return  array(
        'Referer'         => 'https://music.163.com/',
        'Cookie'          => 'appver=1.5.9; os=osx; __remember_me=true; osver=%E7%89%88%E6%9C%AC%2010.13.5%EF%BC%88%E7%89%88%E5%8F%B7%2017F77%EF%BC%89;',
        'User-Agent'      => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko)',
        'X-Real-IP'       => long2ip(mt_rand(1884815360, 1884890111)),
        'Accept'          => '*/*',
        'Accept-Language' => 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',
        'Connection'      => 'keep-alive',
        'Content-Type'    => 'application/x-www-form-urlencoded',
    );
}

function getMusicUrl($ids = ['27969800','1337988206'])
{
    $url = 'http://music.163.com/api/song/enhance/player/url';
    $data = array(
        'ids' => $ids,
        'br'  => 320 * 1000,
    );
    $api = netease_AESCBC($url, $data);
    $url = $api['url'];
    $data = $api['body'];
    $newurl = null;
    $head_arr = setHead();
    $header = array_map(function ($k, $v) {
        return $k . ': ' . $v;
    }, array_keys($head_arr), $head_arr);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if (!is_null($data)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data);
    }
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_IPRESOLVE, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //若给定url自动跳转到新的url,有了下面参数可自动获取新url内容：302跳转
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    //设置cURL允许执行的最长秒数。
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    $content = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $content = json_decode($content,true);
    $data = $content['data'];
    $newurl = [];
    foreach($data as $k=>$v){
       $newurl[$k] = isset($v['url']) ? str_replace("http:", "https:", $v['url']) : null;
    }
    return $newurl;
}


function neteaseHttp($url, $data = false)
{
    $SSL      = substr($url, 0, 8) == "https://" ? true : false; //判断是不是https链接
    $refer    = "http://music.163.com/";
    $header[] = "Cookie: " . "appver=1.5.0.75771;";
    $ch       = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    if ($SSL === true) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if ($data) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_REFERER, $refer);
    $cexecute = curl_exec($ch);
    curl_close($ch);

    if ($cexecute) {
        $result = $cexecute;
        return $result;
    } else {
        return false;
    }
}

function getLyc($id)
{
    $url     = 'http://music.163.com/api/song/lyric?id=' . $id . '&lv=-1&kv=-1';
    $json    = neteaseHttp($url);
    $lyc     = empty($json) ? false : json_decode($json, true);
    $lyc_txt = isset($lyc['lrc']['lyric']) ? $lyc['lrc']['lyric'] : false;
    return $lyc_txt;
}

function search($str)
{
    if ($str) {
        $url      = 'http://music.163.com/api/search/pc';
        $response = neteaseHttp($url, 's=' . urlencode($str) . '&offset=0&limit=10&type=1');
        $json     = json_decode($response, true);
        $list        = isset($json['result']['songs']) ? $json['result']['songs'] : null;
        if (!$list) {
            return false;
        }
        $arr = array();
        foreach ($list as $k => $v) {
            $url = getMusicUrl('http://music.163.com/song/media/outer/url?id=' . $v['id'] . '.mp3');
            if ($url) {
                $arr[$k]['title']  = $v['name'];
                $arr[$k]['author'] = $v['artists'][0]['name'];
                $pic               = $v['album']['picUrl'] . '?param=200y200';
                $arr[$k]['pic']    = str_replace("http:", "https:", $pic);
                $arr[$k]['url']    = str_replace("http:", "https:", $url);
                $arr[$k]['lyc']    = getLyc($v['id']);
            }
        }
        return json_encode($arr);
    }
}

function getJSON($playlist_id,$lyc = false)
{
    $url         = "https://music.163.com/api/playlist/detail?id=" . $playlist_id;
    $response    = neteaseHttp($url);
    $json        = json_decode($response, true);
    $list        = isset($json['result']['tracks']) ? $json['result']['tracks'] : null;
    if (!$list) {
        return false;
    }
    $arr = array();
    foreach ($list as $k => $v) {
        $url = 'http://music.163.com/song/media/outer/url?id=' . $v['id'] . '.mp3';
        $url2 = getMusicUrl([$v['id']]);
        $url2 = isset($url2[0])?$url2[0]: false;
        if ($url2 && $v['id']) {
            $arr[$k]['id'] = $v['id']; 
            $arr[$k]['title']  = $v['name'];
            $arr[$k]['author'] = $v['artists'][0]['name'];
            $pic               = $v['album']['picUrl'] . '?param=300y300';
            $arr[$k]['pic']    = str_replace("http:", "https:", $pic);
            $arr[$k]['url']    = $url2;
            $arr[$k]['url2']    = $url;
            if($lyc === true){
                $arr[$k]['lyc']    = getLyc($v['id']);
            }
        }
    }
    return $arr;
}

function save($playlist_id,$dir = null,$lyc = false,$etime = 600)
{
    if($dir){
        $filename = $dir .'/'. $playlist_id . '.json';
        if (is_file($filename)) {
           $time = time();
           $ftime = filemtime($filename);
           if(($time - $ftime) < $etime){
              return file_get_contents($filename);
           }
        }
    }
    
    $musicLIST = json_encode(getJSON($playlist_id, $lyc));
    if(!empty($musicLIST) && isset($filename)) {
        file_put_contents($filename, $musicLIST);
    }
    return $musicLIST;
}
